package cn.frank.framework.caesar.module.ai.openAi.conf.filter;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/6/5 9:36:15
 * @since 1.8
 */
@Component
@Slf4j
public class RequestIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String path = httpRequest.getRequestURI();

            if (path.startsWith("/api")) {
                String requestId = IdUtil.objectId();
                MDC.put("TraceId", generateTraceId(httpRequest));
            }

            chain.doFilter(request, response);
        } finally {
            MDC.clear(); // 确保清除MDC中的数据
        }
    }

    private String generateTraceId(HttpServletRequest request) {
        // 可以从 Header 中读取已有的 traceId（比如前端或上游服务传来的）
        String traceId = request.getHeader("X-Trace-ID");
        if (traceId == null || traceId.isEmpty()) {
            traceId = IdUtil.objectId();
        }
        return traceId;
    }

    @Override
    public void destroy() {
        // 在销毁时执行清理工作
    }
}